package cn.jobstart.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.net.URLEncoder;

/**
 * @author sunke
 * @Date 2021/1/6 19:57
 * @description 得到城市code
 */


public class City2code {

    public static final String URL = "https://api.jisuapi.com/areacode/city2code";
    public static final String APPKEY = "2359865ac64a0d48";

    public static String getCityCode(String cityName) {
        try {
            String result = null;
            String url = URL + "?appkey=" + APPKEY + "&city=" + URLEncoder.encode(cityName, "utf-8");


            result = HttpTookit.doGet(url, "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if (json.getIntValue("status") != 0) {
                System.out.println(json.getString("msg"));
            } else {
                JSONArray resultarr = json.getJSONArray("result");
                for (int i = 0; i < resultarr.size(); i++) {
                    JSONObject obj = resultarr.getJSONObject(i);
                    String province = obj.getString("province");
                    String city = obj.getString("city");
                    String town = obj.getString("town");
                    String areacode = obj.getString("areacode");
                    return areacode;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0000";
    }
}
